﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using FairyGUI;
using Baiyy;
using Baiyy.Proceduar;
using Baiyy.Resource;
using XLua;

[Hotfix]
/// <summary>
/// 加载流程。
/// </summary>
public class LoadingProceduar : BaseProceduar {

    #region vars
    LoadingWindow _win;
    #endregion

    #region methods
    public LoadingProceduar() {
		name = "LoadingProceduar";
        _win = null;
    }

    void StartLoading() {
		ResourceManager.inst.Load(Config.localVersionFilePath);
    }
    #endregion

    #region delegates
    void OnItemLoading(ResourceManager.LoadItem item) {
        _win.info = "正在加载 " + item.name;
        if (item.retryCount != 0) {
            _win.info += ", " + item.retryCount + "/" + ResourceManager.retryCount;
        }
    }
    void OnItemLoadFailure(ResourceManager.LoadItem item, string error) {
        _win.info = item.name + " 加载失败，" + error;
    }
    void OnItemLoaded(ResourceManager.LoadItem item, int itemLoaded) {
        _win.info = item.name + " 加载完成";
        _win.progress = itemLoaded * 100.0 / ResourceManager.inst.totalItemCount;
    }
    void OnLoadFailure(List<ResourceManager.LoadItem> failedItems) {
        _win.info = "资源加载失败";

        // TODO
    }
    void OnLoadSuccess() {
        _win.info = "资源加载成功";
        _win.progress = 100;

        // TODO
    }
    #endregion

    #region overrides
    /// <summary>
    /// 进入流程。
    /// </summary>
    public override void Enter() {
        ResourceManager.inst.Clear();
        ResourceManager.inst.onItemLoading += OnItemLoading;
        ResourceManager.inst.onItemLoadFailure += OnItemLoadFailure;
        ResourceManager.inst.onItemLoaded += OnItemLoaded;
        ResourceManager.inst.onLoadFailure += OnLoadFailure;
        ResourceManager.inst.onLoadSuccess += OnLoadSuccess;

		ResourceManager.doScriptWhenLoaded = true;
        ResourceManager.inst.Load("/ui/loading.ab", true, (item, error) => {
            if (item != null) {
                UIPackage.AddPackage(item.bundle);
                _win = new LoadingWindow();
                _win.progress = 0;
                _win.info = "正在准备加载...";

                UISystem.inst.Show(_win);

                StartLoading();
            }
            else {
                Console.Error("[LoadingProceduar] 加载资源失败, " + error);
            }
        });
    }
	/// <summary>
	/// 更新流程。
	/// </summary>
	public override void Update() {
	}
	/// <summary>
	/// 离开流程。
	/// </summary>
	public override void Leave() {
        ResourceManager.inst.onItemLoading -= OnItemLoading;
        ResourceManager.inst.onItemLoadFailure -= OnItemLoadFailure;
        ResourceManager.inst.onItemLoaded -= OnItemLoaded;
        ResourceManager.inst.onLoadFailure -= OnLoadFailure;
        ResourceManager.inst.onLoadSuccess -= OnLoadSuccess;
    }
	#endregion
}
